// electron/main.js

// 控制应用生命周期和创建原生浏览器窗口的模组
const { app, BrowserWindow, ipcMain, Menu } = require('electron')
const path = require('path')

const NODE_ENV = process.env.NODE_ENV

function createWindow () {
  // 创建浏览器窗口
  const mainWindow = new BrowserWindow({
    show: false,
    width: 400,
    height: 40,
    frame: false,
    alwaysOnTop: true, // 永远置顶
    resizable: true, // 窗口是否可拉伸
    fullscreenable: false, 
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
    }
  })

  // 加载 index.html
  mainWindow.loadURL(
    NODE_ENV === 'development'
      ? 'http://localhost:3000'
      :`file://${path.join(__dirname, '../dist/index.html')}`
  );

  // 打开开发工具
  if (NODE_ENV === "development") {
    mainWindow.webContents.openDevTools()
  }

  // 清除状态栏
  Menu.setApplicationMenu(null)

  // 定义监听
  // 获取当前窗口位置
  // ipcMain.on('getPositon', function(event){
  //   const pos = mainWindow.getPosition()
  //   event.returnValue = pos
  // })
  // 设置窗口位置
  ipcMain.on('setPosition', (_, pos) => {
    if (!pos) return
    const [x, y] = pos
    mainWindow.setPosition(Number(x), Number(y))
    mainWindow.show()
  })

  mainWindow.on("moved", () => {
    const pos = mainWindow.getPosition()
    mainWindow.webContents.send("getPositon", pos)
  })

}

function createChildWindow() {
  const childWin = new BrowserWindow({
    width: 800,
    height: 500,
    frame: false,
    resizable: false,
    show: false,
    // transparent: true, // 设置透明
    // hasShadow: false, // 不设置阴影
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  childWin.loadURL(
    NODE_ENV === 'development'
      ? 'http://localhost:3000/#/toolbar'
      :`file://${path.join(__dirname, '../dist/index.html/#/toolbar')}`
  );

  // 打开开发工具
  // if (NODE_ENV === "development") {
  //   childWin.webContents.openDevTools()
  // }

  ipcMain.on('create-child-window', () => {
    childWin.show()
  })
  ipcMain.on('close-child-window', () => {
    childWin.hide()
  })
  ipcMain.on("open-tools", () => {
    childWin.webContents.openDevTools()
  })
}

app.whenReady().then(() => {
  createWindow()
  createChildWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// ipcMain.on('getProcess', function(event){
//   event.returnValue = process.versions;
// })


//TODO 拆分模块内容...